import React, { useEffect, useState } from 'react'
import SelectUserModal from '@/pages/components/SelectUserModal';
import { Form, Button, message, Input, Modal, Upload, Row, Col, DatePicker } from 'antd'
import moment from 'moment'
import {UploadOutlined} from '@ant-design/icons';
import { connect } from 'umi'
import { SearchOutlined } from '@ant-design/icons';
import {getUploadUrl} from "@/utils/upload";
import {getEmployeeSalaryModuleByCode} from '@/pages/Salary/Adjustment/service'

const FormItem = Form.Item;
const {TextArea} = Input;

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const CreateForm = (props) => {

  const { onSubmit, onCancel, currentUser, global = {}, visible } = props;
  const { options = {} } = global;
  const { orgLine = [], orgSystem = [], jobLevel = [] } = options;
  const [form] = Form.useForm();
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [info, setInfo] = useState({});
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [fileList, setFileList] = useState([]);

  const fileProps = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    fileList: fileList,
    beforeUpload(file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },
    onChange(info) {
      const {status} = info.file;
      if (status === 'done') {
        if (info.file.response.error) {
          message.success(`${info.file.response.error} 。`);
        } else {
          let urls = fileUploadUrls;
          urls.push(info.file.response);
          setFileUploadUrls(urls);
          message.success(`${info.file.name} 文件上传成功。`);
        }
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败。`);
      }
      let files = info.fileList.filter(item => item.status);
      setFileList(files);
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  useEffect(() => {
    if (visible){
      let data = {};
      data.applyName = currentUser.name;
      data.applyUnitId = currentUser.depId;
      data.applyUnitName = currentUser.department;
      data.applyJobName = currentUser.jobname;
      data.applyTime = moment();
      setInfo(data);
      form.setFieldsValue(data);
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    setInfo(null);
    onCancel();
    setFileUploadUrls([]);
    uploadedFiles = [];
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    onSubmit({...fieldsValue, type: 5, fileUrls: fileUploadUrls});
    setInfo(null);
    form.resetFields();
    setFileUploadUrls([]);
    uploadedFiles = [];
  };

  const showSelectUserModal = () =>{
    setUserModalVisible(true);
  };

  const confirmSelectUser = (usersInfo) =>{
    if (usersInfo.length>0){
      let userInfo = usersInfo[0];
      userInfo.jobLevel = userInfo.jobLevelId ? jobLevel.find(item => item.id===userInfo.jobLevelId)?.name : '';
      let data = {...info, ...userInfo};
      setInfo(data);
      getEmployeeSalaryModuleByCode(data.code).then(res => {
        let obj ={
          standardMonthlySalary: res.total,
          baseSalary: res.bsalaryBase,
          moduleSalaryBase: res.mkBases,
        };
        form.setFieldsValue({...data, ...obj});
        setUserModalVisible(false);
      });
    }else {
      message.error('请选择人员!')
    }
  };

  const cancelSelectUser = () => {
    setUserModalVisible(false);
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="applyName" label="申请人">
              <Input disabled />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyTime" label="申请调整日期" rules={[{required: true, message: '请输入申请调整日期！'}]}>
              <DatePicker className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyUnitName" label="申请人部门">
              <Input disabled />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyJobName" label="申请人职位">
              <Input disabled />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <Form.Item label="姓名" name='name' rules={[{required: true, message: '请选择人员！'}]}>
              <Input.Group compact size="large">
                <Input style={{ width: '80%',height: '32px', fontSize:'14px', background: '#ffffff' }} placeholder="选择人员" value={info ? info.name : ''} disabled={true}/>
                <Button style={{ width: '20%' }} icon={<SearchOutlined/>} onClick={() => showSelectUserModal()} />
              </Input.Group>
            </Form.Item>
          </Col>
          <Col span={0}>
            <FormItem name="oid" label="员工Id">
              <Input disabled />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitname" label="部门名称">
              <Input disabled />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="岗位">
              <Input disabled />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobLevel" label="职级">
              <Input disabled />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="standardMonthlySalary" label="现月薪标准">
              <Input disabled />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="baseSalary" label="现基本工资基数">
              <Input disabled />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="moduleSalaryBase" label="现模块工资基数">
            <Input disabled />
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="remark" labelCol={{span: 2}} label="说明" rules={[{required: true, message: '请输入薪资变动说明！'}]}>
              <TextArea rows={8} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col span={24}>
            <Upload {...fileProps}>
              <Button>
                <UploadOutlined/> 点击上传附件
              </Button>
            </Upload>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      width={1280}
      destroyOnClose
      title="薪资调整"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>

      <SelectUserModal
        selectType={0}
        isOrgGroupFilter={true}
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={cancelSelectUser}
      />
    </Modal>
  )
};


export default connect(({ user, global }) => ({
  global,
  currentUser: user.currentUser,
}))(CreateForm)
